package com.qf.shop.service.impl;

import com.qf.shop.dao.CartDao;
import com.qf.shop.dao.Impl.CartDaoImpl;
import com.qf.shop.dao.Impl.OrdersDaoImpl;
import com.qf.shop.dao.OrdersDao;
import com.qf.shop.entity.Cart;
import com.qf.shop.entity.Orders;
import com.qf.shop.entity.OrdersDetail;
import com.qf.shop.service.OrdersService;
import com.qf.shop.utils.DruidUtils;

import java.util.ArrayList;
import java.util.List;

public class OrdersServiceImpl implements OrdersService {
    private OrdersDao ordersDao = new OrdersDaoImpl();
    private CartDao cartDao = new CartDaoImpl();
    @Override
    public int createOrders(Orders orders) {
        try {
            DruidUtils.begin();
            //1.向数据库插入一条orders数据
            ordersDao.insertOrders(orders);
            //2.创建订单详情集合
            List<OrdersDetail> ordersDetails = new ArrayList<>();
            //3.获取购物车集合  购物车每条数据都对应着订单详情的一条数据
            List<Cart> carts = cartDao.selectById(orders.getUid());
            for (Cart cart :carts){
                //每循环一个购物车的对象，就生成一条订单详情,跟购物车，订单，有关
                OrdersDetail ordersDetail = new OrdersDetail(cart.getGid(),orders.getId(),cart.getNum(),cart.getMoney());
                ordersDetails.add(ordersDetail);
            }
            //4.订单保存订单详情
            ordersDao.insertOrdersDetail(ordersDetails);
            //5.清空购物车
            cartDao.deleteById(orders.getUid());
            DruidUtils.commit();
        } catch (Exception e) {
            DruidUtils.rollback();
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public List<Orders> selectAllOrdersByUid(int uid) {
        List<Orders> orders =null;

        try {
            DruidUtils.begin();
            orders =ordersDao.selectOrdersByUid(uid);
            DruidUtils.commit();
        } catch (Exception e) {
            DruidUtils.rollback();
            e.printStackTrace();
        }
        return orders;
    }

    @Override
    public Orders selectOrdersByOid(String oid) {
        Orders orders =null;
        try {
            DruidUtils.begin();
            //1.根据oid查询订单和订单地址信息
            orders = ordersDao.selectOrdersByOid(oid);
            //2.根据oid查询订单详情和商品信息。
            List<OrdersDetail> ordersDetails = ordersDao.selectOrdersDetailByOid(oid);
            //3.将订单详情集合保存在orders里（每个订单项对象都包含了一个商品）
            orders.setList(ordersDetails);
            DruidUtils.commit();
        } catch (Exception e) {
            DruidUtils.rollback();
            e.printStackTrace();
        }
        return orders;
    }

    @Override
    public int updateOrdersStatus(String oid) {
        int result = 0;
        try {
            DruidUtils.begin();
            result = ordersDao.updateOrders(oid);
            DruidUtils.commit();
        } catch (Exception e) {
            DruidUtils.rollback();
            e.printStackTrace();
        }
        return result;
    }
}
